import {  constantRoutes } from '@/router'
import { getUserMenus } from "@/api/user";
import Layout from "@/layout";
import ParentView from '@/components/parentView'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  menus:[]
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUS: (state,menus) =>{
    state.menus = menus;
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      getUserMenus().then(res =>{
        let menus = res.data||[];
        const routes = [];
        const baseRouter =  {
            path: '/',
            component: Layout,
            redirect: '/dashboard',
            children: [
              {
                path: 'dashboard',
                component: () => import('@/views/dashboard/index'),
                name: 'Dashboard',
                meta: { title: '仪表盘', icon: 'dashboard', affix: true }
              },
              {
                path: 'profile',
                component:ParentView,
                redirect: '/profile/index',
                hidden:true,
                children: [
                  {
                    path: 'index',
                    component: () => import('@/views/profile/index'),
                    name: 'Profile',
                    meta: { title: 'Profile', icon: 'user', noCache: true }
                  }
                ]
              }
            ]
          };
        routes.push(baseRouter)
        generaMenu(baseRouter.children,menus,{})
        routes.push(  { path: '*', redirect: '/404', hidden: true } );
        let accessedRoutes = routes||[];
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_MENUS',baseRouter.children);
        resolve(accessedRoutes)
      })
    })
  }
}

/**
 * 顶层菜单
 * @param rotes
 * @param data
 */
function generaMenu(routes,data,map){
  data.forEach(item => {
    const menu = {
      path: item.url,
      component: (item.children && item.children.length > 0) ? ParentView : loadView(item.component),
      children: [],
      name: 'menu_' + item.id,
      meta: {title: item.name, icon: item.icon, noCache: true,  }
    }
    if (item.children) {
      generaMenu(menu.children, item.children,map)
    }
    routes.push(menu)
  })
}



export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
